<template>
  <div>
    <!-- 资源管理表格 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>资源管理</span>
        <el-form :inline="true" class="demo-form-inline">
          <el-popover v-model="visible" class="delete" placement="top" width="160">
            <p>确定删以下用户吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="handleBatchDel">确定</el-button>
            </div>
            <el-button slot="reference" icon="el-icon-delete" type="danger" size="mini">批量删除 </el-button>
          </el-popover>
        </el-form>
      </div>
      <!-- 资源管理表格 -->
      <el-table :data="tableData" row-key="id" :tree-props="defaultProps" @selection-change="selsChange">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="order" label="排序" />
        <el-table-column prop="name" label="资源名称" :show-overflow-tooltip="true" width="160" />
        <el-table-column prop="extend" label="资源图标" :show-overflow-tooltip="true" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.extend">{{ JSON.parse(scope.row.extend).icon }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="资源类型" width="200" />
        <el-table-column prop="level" label="层级" :show-overflow-tooltip="true" />
        <el-table-column prop="desc" label="描述" :show-overflow-tooltip="true" />
        <el-table-column prop="url" label="请求路径" :show-overflow-tooltip="true" />
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.id)">编辑</el-button>
            <!-- 新增按钮 -->
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row.parentId)">新增</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增资源弹框 -->
    <el-dialog width="700px" :visible.sync="open" :title="title">
      <el-form ref="formList" label-width="120px" :model="formList" :rules="rules">
        <el-form-item label="资源类型" prop="type">
          <el-input v-model="formList.type" size="small" placeholder="请输入资源类型" />
        </el-form-item>
        <el-form-item label="资源名" prop="name">

          <!-- 资源名称输入框 -->
          <el-input v-model="formList.name" size="small" placeholder="请输入资源名" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
            <IconSelect ref="iconSelect" :active-icon="formList.extend.icon" @selected="selected" />
            <el-input slot="reference" v-model="formList.extend.icon" placeholder="点击选择图标" readonly>
              <svg-icon
                v-if="formList.extend.icon"
                slot="prefix"
                :icon-class="formList.extend.icon"
                style="width: 25px;"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="显示排序" prop="order">
          <!-- 显示排序输入框 -->
          <el-input v-model.number="formList.order" size="small" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="路由地址" prop="url">
          <!-- 路由地址输入框 -->
          <el-input v-model="formList.url" size="small" placeholder="请输入路由地址" />
        </el-form-item>

        <el-form-item label="层级" prop="level">
          <!-- 路由地址输入框 -->
          <el-input v-model="formList.level" size="small" placeholder="请输入层级" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <!-- 路由地址输入框 -->
          <el-input v-model="formList.desc" type="textarea" placeholder="请输入资源描述" />
        </el-form-item>
        <!-- 确认和取消按钮 -->
        <el-form-item>
          <el-button size="mini" type="primary" @click="handleSave">确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listRole, addRole, updateRole, deleteRole, getRole } from '@/api/business/resource'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
export default {
  components: { IconSelect },
  data() {
    return {
      title: '新增资源',
      visible: false,
      open: false,
      sels: '',
      queryParams: {
        name: ''
      },
      // 渲染数据
      tableData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储数据
      formList: {
        extend: {
          icon: null
        }
      },
      rules: {
        type: [{ required: true, message: '资源类型不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '资源名不能为空', trigger: 'blur' }],
        url: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
        order: [{ required: true, message: '排序不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!Number.isInteger(value)) {
                callback(new Error('排序必须是数字类型'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }],
        level: [
          { required: true, message: '层级不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '资源描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 加载数据
    this.fetchData()
  },
  methods: {
    // 选择图标
    selected(name) {
      var extend = {
        'icon': name
      }
      this.formList.extend = extend
    },
    // 加载数据
    async fetchData() {
      try {
        const res = await listRole()
        this.tableData = res
        console.log(this.tableData)
      } catch (error) {
        console.error(error)
        // 处理错误，例如给用户提示错误信息
      }
    },
    // 新增弹框
    handleAdd(parentId) {
      this.open = true
      this.title = '新增资源'
      this.formList.parentId = parentId
      this.reset()
    },
    // 新增资源方法
    async handleSave() {
      this.formList.extend = JSON.stringify(this.formList.extend)
      if (this.formList.id) {
        // 编辑操作
        const res = await updateRole(this.formList) // 更新资源数据
        const result = {
          success: res // 将布尔值作为对象属性
        }
        if (result.success) {
          this.$message.success('编辑资源成功')
        } else {
          this.$message.error('编辑资源失败')
        }
      } else {
        // 新增操作
        const res = await addRole(this.formList) // 添加资源数据
        const result = {
          success: res // 将布尔值作为对象属性
        }

        if (result.success) {
          this.$message.success('新增资源成功')
        } else {
          this.$message.error('新增资源失败')
        }
      }

      this.open = false
      this.fetchData()
    },

    // 编辑弹窗
    async handleUpdate(id) {
      this.open = true
      const res = await getRole(id)
      console.log(res)
      this.formList = res
      this.formList.extend = JSON.parse(res.extend) // 将 extend 字符串转换为对象
      this.title = '编辑资源'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.fetchData()
    },
    pocket() {
      this.cancel = false
      this.reset()
      this.fetchData()
    },
    // 清空表单
    reset() {
      this.formList = {
        type: '',
        level: '',
        order: '',
        name: '',
        desc: '',
        url: '',
        extend: ''
      }
      this.fetchData()
    },
    // 批量删除勾选存储数据
    selsChange(row) {
      this.sels = [...row]
      console.log(this.sels)
    },
    // 批量删除
    async handleBatchDel() {
      const idsAsString = this.sels.map(item => item.id.toString())
      try {
        await deleteRole(idsAsString)
        this.$message('删除成功')
        this.visible = false
        this.fetchData()
      } catch (error) {
        console.error(error)
        // this.$message.error("删除失败");
      }
    }

  }
}

</script>
<style lang="scss" scoped>
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 95%;
  margin: 30px;
}

.tou {
  margin-bottom: 10px;
}

.bot {
  margin-top: 10px;
}

.top {
  margin-top: 20px;
}

.input {
  width: 200px;
}

.search {
  margin-left: 10px;
}

.demo-form-inline {
  margin-top: 20px;
}
</style>
